<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="主题">
              <a-input placeholder="请输入主题" v-model="queryParam.theme"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="openModal('add', {})" type="primary" icon="plus">新增</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown>
    </div>

    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="fileName" slot-scope="text, record">
          <a slot="fileName" :href="record.url" target="_blank">{{ text }}</a>
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="openModal('edit', record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a style="color: red;">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>

    <a-modal
      :visible="visible"
      :width="500"
      :title="curRowType === 'add' ? '新增政策' : '编辑政策'"
      :confirmLoading="submitLoad"
      destroyOnClose
      @cancel="handleCancel"
      @ok="handleOperate"
    >
      <a-spin :spinning="spinning">
        <a-form-model ref="ruleForm" :model="formData" layout="vertical">
          <a-form-model-item
            label="主题"
            prop="theme"
            :rules="{
              required: true,
              message: '请输入主题',
              trigget: 'blur'
            }"
          >
            <a-input v-model="formData.theme" placeholder="请输入主题" :maxLength="200" />
          </a-form-model-item>
          <a-form-model-item
            label="文件"
            prop="fileList"
            :rules="{
              type: 'array',
              required: true,
              message: '请上传文件',
              trigget: 'blur'
            }"
          >
            <a-upload
              v-if="Array.isArray(formData.fileList) && formData.fileList.length === 0"
              ref="uploadRef"
              name="file"
              :action="actionUrl"
              :headers="{
                'X-Access-Token': $store.state.user.token
              }"
              :remove="() => (formData.fileList = [])"
              :beforeUpload="beforeUpload"
              @change="handleChange"
              :showUploadList="false"
            >
              <a-button> <a-icon type="upload" /> 文件上传 </a-button>
            </a-upload>
            <div class="file_item" v-for="item in formData.fileList" :key="item.fileId">
              <span>{{ item.fileName }}</span> <span @click="delFile"><a-icon type="delete"/></span>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { apiAddPolicyDoc, apiEditPolicyDoc, apiDelPolicyDoc } from '@/api/policyDoc'

export default {
  name: 'PolicyDoc',
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      description: '政策文档管理',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '主题',
          align: 'center',
          dataIndex: 'theme'
        },
        {
          title: '文件',
          align: 'center',
          dataIndex: 'fileName',
          scopedSlots: { customRender: 'fileName' }
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/gzPolicyDocument/list',
        delete: '/gzPolicyDocument/delete',
        deleteBatch: '/gzPolicyDocument/deleteBatch'
      },
      curType: '',
      curStatus: '',
      customId: '',
      packagePriceId: undefined,
      visible: false,
      modalTitle: '新增政策',
      submitLoad: false,
      formData: {
        theme: '',
        fileList: []
      },
      curRow: {},
      curRowType: 'add',
      spinning: false
    }
  },
  created() {},
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    userType() {
      return this.$store.state.user.info.userType
    },
    actionUrl() {
      return process.env.VUE_APP_API_BASE_URL + '/api/file/upload'
    }
  },
  methods: {
    handleQuotation(record) {
      this.curType = record.userType
      this.customId = record.id
      this.curStatus = 'operate'
      this.packagePriceId = record.packagePriceId
      this.$refs.QuotationModalRef.visible = true
    },
    openModal(type, row) {
      this.curRowType = type
      this.curRow = row
      this.visible = true
      if (type !== 'add') {
        const { fileId, fileName, url, id, theme } = row
        this.formData = {
          id,
          theme,
          fileList: [
            {
              fileName,
              fileId,
              url
            }
          ]
        }
      }
    },
    async handleOperate() {
      const apiFun = this.curRowType === 'add' ? apiAddPolicyDoc : apiEditPolicyDoc
      const params = { theme: this.formData.theme, ...this.formData.fileList[0], id: this.curRow.id }
      await this.$refs.ruleForm.validate()
      this.submitLoad = true
      const { code, message } = await apiFun(params)
      this.submitLoad = false
      if (code === 200) {
        this.handleCancel()
        this.searchQuery()
        this.$message.success('操作成功！')
      } else {
        this.$message.success(message)
      }
    },
    handleCancel() {
      this.visible = false
      this.formData = {
        theme: '',
        url: ''
      }
    },
    // 上传前
    beforeUpload(file) {
      const { type, size } = file
      console.log(type, 'typetype')
      if (
        ![
          'application/pdf',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ].includes(type)
      ) {
        this.$message.error('只能上传pdf或word文件！')
        return Promise.reject()
      }
      if (10 * 1024 * 1024 < size) {
        this.$message.error('文件最大为10M！')
        return Promise.reject()
      }
      this.spinning = true
      return Promise.resolve(file)
    },
    // 文件上传
    handleChange({ file }) {
      const { status, response } = file
      if (status === 'done') {
        const { code, result } = response
        this.spinning = false
        if (code === 0) {
          const { fileId, name: fileName, url } = result
          this.formData.fileList = [
            {
              fileName,
              fileId,
              url
            }
          ]
        }
      }
    },
    delFile() {
      this.formData.fileList = []
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.file_item {
  margin: 10px 0;
  padding: 5px;
  display: flex;
  justify-content: space-between;
  align-content: center;
  font-size: 14px;
  border-radius: 2px;
  cursor: pointer;
}
.file_item:hover {
  background-color: #e6f7ff;
  color: #40a9ff;
}
</style>
